#!/usr/bin/env python
# -*-coding=utf-8-*-
__author__ = '李元'

import base64
import re
import requests
import urllib
import binascii
import rsa
import time
import json
from bs4 import BeautifulSoup
from scpy.logger import get_logger

req = requests.Session()
logger = get_logger(__file__)
headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'en-US,en;q=0.8',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    'Host': 'weibo.com',
    'Upgrade-Insecure-Requests': 1,
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'
}
req.headers['Referer'] = 'http://weibo.com'
req.headers[
    'User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'


def login_weibo(username, password):
    try:
        prelogin_url = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCal' \
                       'lBack&su=%s&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.18)&_=1447731207967' % username
        pre_login_data = req.get(prelogin_url, allow_redirects=False).content
        servertime = re.findall('"servertime":(.*?),', pre_login_data)[0]
        pubkey = re.findall('"pubkey":"(.*?)",', pre_login_data)[0]
        rsakv = re.findall('"rsakv":"(.*?)",', pre_login_data)[0]
        nonce = re.findall('"nonce":"(.*?)",', pre_login_data)[0]
        su = base64.b64encode(bytes(urllib.quote(username)))
        rsa_publickey = int(pubkey, 16)
        key = rsa.PublicKey(rsa_publickey, 65537)
        message = bytes(str(servertime) + '\t' + str(nonce) + '\n' + str(password))
        sp = binascii.b2a_hex(rsa.encrypt(message, key))
        param = {
            'entry': 'weibo',
            'gateway': 1,
            'from': '',
            'savestate': 7,
            'useticket': 1,
            'pagerefer': 'http://login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl%3D',
            'vsnf': 1,
            'su': su,
            'service': 'miniblog',
            'servertime': servertime,
            'nonce': nonce,
            'pwencode': 'rsa2',
            'rsakv': rsakv,
            'sp': sp,
            'sr': '1680*1050',
            'encoding': 'UTF-8',
            'prelt': 441,
            'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
            'returntype': 'META'
        }
        data = urllib.urlencode(param).encode('utf-8')
        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        res = req.post('http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)', data)
        urll = re.findall("location.replace\(\'(.*?)\'\);", res.content)[0]
        req.get(urll)
        req.headers.update({'Referer': 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)'})
        req.get(
            'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack&sudaref=weibo.com')
        return True
    except Exception, e:
        print e
        logger.error('login failed, username:' + username + ',password:' + password + ',error info:' + e)
        return False


def send_text(text):
    url = 'http://weibo.com/aj/mblog/add?ajwvr=6&__rnd=%s' % int(time.time() * 1000)
    print url
    data = {
        'location': 'v6_content_home',
        'appkey': '',
        'style_type': '1',
        'pic_id': '',
        'text': text,
        'pdetail': '',
        'rank': '0',
        'rankid': '',
        'module': 'stissue',
        'pub_source': 'main_',
        'pub_type': 'dialog',
        '_t': '0'
    }
    data = urllib.urlencode(data).encode('utf-8')
    req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    req.headers['Referer'] = 'http://weibo.com/liyuantgg/home?wvr=5&lf=reg'
    req.post(url, data)
    return


def web_service():
    url = 'http://apis.baidu.com/heweather/weather/free?city=' + '重庆'
    req.headers.update({'apikey': 'ee87c22e2a82c2d399b90cb5408549ba'})
    res = req.post(url)
    aqi = json.JSONDecoder().decode(res.content)['HeWeather data service 3.0'][0]['aqi']['city']
    basic = json.JSONDecoder().decode(res.content)['HeWeather data service 3.0'][0]['basic']['update']
    tem = json.JSONDecoder().decode(res.content)['HeWeather data service 3.0'][0]['now']
    suggestion = json.JSONDecoder().decode(res.content)['HeWeather data service 3.0'][0]['suggestion']
    return_info = u'重庆' + \
                  u' 天气情况:' + tem['cond']['txt'] + \
                  u' 空气质量:' + aqi['qlty'] + \
                  u' pm2.5:' + aqi['pm25'] + \
                  u' 更新时间' + basic['loc'] + \
                  u' 体感温度:' + tem['tmp'] + \
                  u' ' + suggestion['drsg']['txt'] + \
                  u' ' + suggestion['flu']['txt']
    print return_info
    return return_info.encode('utf-8')


if __name__ == '__main__':
    send_text('重庆')
    if login_weibo('username','password'):
        text = web_service()
        send_text(text)
    else:
        print 'login failed'
